<template>
  <q-field v-model="modelValue" borderless no-error-icon>
    <template v-for="item in Object.keys(useSlots())" v-slot:[item]>
      <slot :name="item"></slot>
    </template>
    <template v-slot:control="{ id }">
      <q-checkbox v-if="showAll" v-model="selectedAll" :label="$t('CheckAll')" class="q-mr-sm" v-bind="$attrs"
                  @update:model-value="updateAll" />
      <q-option-group :id="id" v-model="modelValue" :disable="readonly" :options="options" :type="type" v-bind="$attrs"
                      @update:model-value="updateGroup" />
    </template>
  </q-field>
</template>

<script setup>
import { computed, ref, useSlots } from 'vue'

const props = defineProps({
  type: { type: String, default: 'radio' },
  options: Array, allBtn: Boolean, single: Boolean, change: Function, outlined: Boolean, readonly: Boolean
})
const emits = defineEmits(['change'])
const modelValue = defineModel('modelValue', { type: [String, Number, Array, Boolean] })

const selectedAll = ref(false)
const isRadio = computed(() => props.type === 'radio')
const showAll = computed(() => !isRadio.value && !props.single && props.allBtn && props.options?.length)

const setSelectedAll = (value = [], options = []) => {
  if (!showAll.value) return
  if (options?.length === value?.length) selectedAll.value = true
  else if (value?.length === 0) selectedAll.value = false
  else selectedAll.value = null
}
const updateAll = value => {
  if (!value) return updateGroup([])
  const list = (props.options || []).map(el => el.value)
  updateGroup(list)
}
const updateGroup = value => {
  if (props.single && value.length > 1) value = [value[1]]
  if (props.change) props.change(value)
  else emits('change', value)
  setSelectedAll(value, props.options)
}
</script>